using System.Collections;
using System.Linq;
using UnityEngine;
using YooAsset;

namespace LFrameworkAOT
{
    public class GameLaunch : MonoBehaviour
    {
        //全局参数设置
        [SerializeField]
        private ParamsSettings m_ParamsSettings;
        public static ParamsSettings ParamsSettings { get; private set; }

        /// <summary>
        /// 资源系统运行模式
        /// </summary>
        public EPlayMode PlayMode = EPlayMode.EditorSimulateMode;

        public static GameLaunch Instance { get; private set; }
        private void Awake()
        {
            Instance = this;
            ParamsSettings = m_ParamsSettings;
            DontDestroyOnLoad(this.gameObject);
        }

        IEnumerator Start()
        {
            // 初始化资源系统
            YooAssets.Initialize();

            // 加载更新页面
            GameObject checkPatchPrefab = Resources.Load<GameObject>("CheckPatch");
            GameObject checkPatchGo = GameObject.Instantiate(checkPatchPrefab);

            //找到 patch 界面，用来显示更新信息等
            PatchWindow patchWindow = checkPatchGo.transform.Find("PatchWindow").GetComponent<PatchWindow>();

            // 开始补丁更新流程
            var operation = new PatchOperation(ParamsSettings.PackageName, PlayMode,patchWindow);
            YooAssets.StartOperation(operation);
            yield return operation; 

            // 设置默认的资源包
            ResourcePackage gamePackage = YooAssets.GetPackage(ParamsSettings.PackageName);
            YooAssets.SetDefaultPackage(gamePackage);

            //加载热更dll
            HotfixCtrl hotfixCtrl = new HotfixCtrl();
            yield return hotfixCtrl.LoadHotifx();

            //加载 gameEntry 资源
            AssetHandle gameEntryHandle = YooAssets.LoadAssetAsync<GameObject>("Assets/Download/GameEntry/GameEntry.prefab");
            yield return gameEntryHandle;

            checkPatchGo.SetActive(false);
            //实例化 GameEntry, 这个是游戏启动的入口
            Instantiate(gameEntryHandle.AssetObject);
        }

        private void Update()
        {
            
        }

        #region log 接口
        public static void Log(params object[] args)
        {
#if DEBUG_LOG_NORMAL
            Debug.Log("MainEntryLog - " + args.Aggregate("", (current, message) => current + (" - " + message)));
#endif
        }

        public static void LogWarning(params object[] args)
        {
#if DEBUG_LOG_WARNING
            Debug.LogWarning("MainEntryLog - " + args.Aggregate("", (current, message) => current + (" - " + message)));
#endif
        }

        public static void LogError(params object[] args)
        {
#if DEBUG_LOG_ERROR
            Debug.LogError("MainEntryLog - " + args.Aggregate("", (current, message) => current + (" - " + message)));
#endif
        }
        #endregion
    }
}